import os
import yaml


# 1. 创建类
class YamlReader:
    # 2. 初始化方法, 判断文件是否存在
    def __init__(self, yamlfile):
        if os.path.exists(yamlfile):
            self.yamlf = yamlfile
        else:
            raise FileNotFoundError("文件不存在")
        self._data = None  # 默认没有读取过文件
        self._data_all = None  # 默认没有读取过文件

    # 定义方法, Yaml读取单个文档、多个文档
    def read_data(self):
        if not self._data:  # 判断是否有读取文件
            with open(self.yamlf, "r", encoding="utf8") as f:
                self._data = yaml.safe_load(f)
        return self._data

    def read_all(self):
        if not self._data_all:  # 判断是否有读取文件
            with open(self.yamlf, "r", encoding="utf8") as f:
                self._data_all = list(yaml.safe_load_all(f))
        return self._data_all
